package com.dingreading.cloud.web.util.wxgzh;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.util.HttpUtils;
import com.dingreading.cloud.common.util.wechat.PayConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信服务号接口请求工具
 */
public class GzhUrlUtils {

    private static final Logger logger = LoggerFactory.getLogger(GzhUrlUtils.class);


    public static JSONObject getUserInfo(String openId, String accessToken) {
        JSONObject object = null;
        try {
            String url = String.format(PayConfig.USER_INFO_URL, accessToken, openId);
            String result = HttpUtils.get(url);
            if (StringUtils.isNotBlank(result)) {
                object = JSONObject.parseObject(result);
            } else {
                System.out.println("获取关注服务号的用户信息，失败");
                System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * 发送模板消息
     */
    public static JSONObject sendTemplate(String data, String accessToken) {
        JSONObject object = null;
        try {
            String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
            String result = HttpUtils.post(requestUrl, data);
            if (StringUtils.isNotBlank(result)) {
                object = JSONObject.parseObject(result);
                Integer errcode = object.getInteger("errcode");
                if (errcode == null || errcode != 0) {
                    logger.error("发送模板消息，失败：" + result);
                }
            } else {
                logger.error("发送模板消息，失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * 创建临时带参数二维码
     * 获取灵石带参二维码ticket
     *
     * @param accessToken
     * @param sceneId     场景Id
     * @return
     * @expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
     */
    public static String createTempTicket(String accessToken, String expireSeconds, int sceneId) {
        Map<String, Integer> intMap = new HashMap<>();
        intMap.put("scene_id", sceneId);
        Map<String, Map<String, Integer>> mapMap = new HashMap<>();
        mapMap.put("scene", intMap);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("expire_seconds", expireSeconds);
        paramsMap.put("action_name", "QR_SCENE");
        paramsMap.put("action_info", mapMap);
        String jsonObject = JSONObject.toJSONString(paramsMap);
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        String result = HttpUtils.post(requestUrl, jsonObject);
        return result;
    }

    /**
     * 创建永久二维码(数字)
     *
     * @param accessToken
     * @param sceneId     场景Id
     * @return
     */
    public static String createForeverTicket(String accessToken, int sceneId) {
        Map<String, Integer> intMap = new HashMap<>();
        intMap.put("scene_id", sceneId);
        Map<String, Map<String, Integer>> mapMap = new HashMap<>();
        mapMap.put("scene", intMap);
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("action_name", "QR_LIMIT_SCENE");
        paramsMap.put("action_info", mapMap);
        String jsonObject = JSONObject.toJSONString(paramsMap);
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        String result = HttpUtils.post(requestUrl, jsonObject);
        return result;
    }

    /**
     * 创建永久二维码(字符串)
     *
     * @param accessToken
     * @param sceneStr    场景str
     * @return
     */
    public static String createForeverStrTicket(String accessToken, String sceneStr) {
        if (StringUtils.isBlank(sceneStr))
            sceneStr = "0";

        JSONObject inObj = new JSONObject();
        inObj.put("scene_str", sceneStr);

        JSONObject sceneObj = new JSONObject();
        sceneObj.put("scene", inObj);

        JSONObject param = new JSONObject();
        param.put("action_name", "QR_LIMIT_STR_SCENE");
        param.put("action_info", sceneObj);

        String jsonObject = param.toJSONString();
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        String result = HttpUtils.post(requestUrl, jsonObject);
        return result;
    }

    /**
     * 公众号创建自定义创建菜单
     * {"button":[{"name":"领取门票","type":"view","url":"https://www.dingreading.com/"},{"name":"大会介绍","type":"view","url":"https://www.dingreading.com/"},{"name":"参会指南","type":"view","url":"https://www.dingreading.com/"}]}
     */
    public static String createMenus(String accessToken) {
//        String baseUrl = "https://acec.dingreading.com";
        String baseUrl = "https://www.myacec.com";
        JSONArray buttons = new JSONArray();
        JSONObject button1 = new JSONObject();
        button1.put("type", "view");
        button1.put("name", "大会直播");
        button1.put("url", baseUrl + "/e");
        buttons.add(button1);

        JSONArray subButton = new JSONArray();
//        JSONObject subButton1 = new JSONObject();
//        subButton1.put("type", "view");
//        subButton1.put("name", "住宿预订");
//        subButton1.put("url", baseUrl + "/b");
//        subButton.add(subButton1);
        JSONObject subButton2 = new JSONObject();
        subButton2.put("type", "view");
        subButton2.put("name", "交通指南");
        subButton2.put("url", baseUrl + "/c");
        subButton.add(subButton2);
        JSONObject subButton3 = new JSONObject();
        subButton3.put("type", "view");
        subButton3.put("name", "美食推荐");
        subButton3.put("url", baseUrl + "/d");
        subButton.add(subButton3);

        JSONObject button2 = new JSONObject();
        button2.put("name", "大会服务");
        button2.put("sub_button", subButton);
        buttons.add(button2);

        JSONObject button3 = new JSONObject();
        button3.put("type", "view");
        button3.put("name", "票务中心");
        button3.put("url", baseUrl);
        buttons.add(button3);

        JSONObject buttonObj = new JSONObject();
        buttonObj.put("button", buttons);

        String param = buttonObj.toJSONString();
//        System.out.println("菜单参数 = " + param);

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
        String result = HttpUtils.post(requestUrl, param);
        return result;
    }

    /**
     * 公众号删除自定义菜单
     */
    public static String dropMenus(String accessToken) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + accessToken;
        String result = HttpUtils.get(requestUrl);
        return result;
    }

}
